import tornado.web
import json
import logging
import datetime

from util.db import connect_db


class BaseHandler(tornado.web.RequestHandler):
    def initialize(self):
        if self.request.method in ("PUT", "POST"):
            logging.info(self.request.body.decode("utf8"))
            logging.info(json.loads(self.request.body.decode("utf8")))
            self.get_body()
        self.db = connect_db()

    def valid_user(self):
        return

    def get_body(self):
        self.body = json.loads(self.request.body.decode("utf8"))

    def get_body_para(self, name):
        if name in self.body:
            return self.body[name]
        else:
            return None

    def rsp(self, code, data={}, msg=''):
        content = {}
        content["code"] = code
        content["data"] = data
        content["msg"] = msg
        self.write(content)
        logging.info(content)


class AuthHandler(BaseHandler):
    def prepare(self):
        if 'Token' in self.request.headers:
            logging.info(self.request.headers['Token'])
            sql = 'SELECT * FROM users WHERE token = \'' + self.request.headers['Token'] + '\''
            # res = self.db.get(sql, self.request.headers['Token'])
            res = self.db.get(sql)
            if res and res.expire > datetime.datetime.now():
                self.user = res
                logging.info(self.user)
                return
        logging.info("401")
        self.send_error(status_code=401)



